package com.kun.sync;

import java.sql.SQLException;
import java.util.concurrent.Executors;

import com.kun.sync.processor.DefaultConvertProcessor;
import com.kun.sync.reader.SourceReader;
import com.kun.sync.step.StepFactory;
import com.kun.sync.writer.BatchWriter;

/**
 * 简单执行器
 * 
 * @author zjkorder (2018/1/30 11:12)
 */
public class SimpleExecute {

	public static void executeInsert(String[] sourceDatabaseConfig, String[] targetDatabaseConfig,
			String sourceTableName, String targetTableName, String[] insertFieldArray) throws SQLException {
		SourceReader sourceReader = new SourceReader(sourceDatabaseConfig, sourceTableName, null, null, null, 10000);
		DefaultConvertProcessor processor = new DefaultConvertProcessor(null, null, insertFieldArray);
		BatchWriter insert = insert(targetDatabaseConfig, targetTableName, insertFieldArray, 10000);
		StepFactory.start(sourceReader, processor, insert, Executors.newFixedThreadPool(7));
	}

	/**
	 * 插入
	 *
	 * @param databaseConnectionConfig 数据库连接配置
	 * @param insertFieldArray 插入字段
	 * @return BatchWriter
	 */
	public static BatchWriter insert(String[] databaseConnectionConfig, String tableName, String[] insertFieldArray,
			int limit) throws SQLException {
		String insertSQL;
		{
			// 初始化插入SQL
			StringBuilder valueField = new StringBuilder();
			StringBuilder value = new StringBuilder();
			for (String field : insertFieldArray) {
				valueField.append(",\"").append(field).append("\"");
				value.append(",").append("?");
			}
			insertSQL = "insert into " + tableName + " (" + valueField.toString().replaceFirst(",", "") + ") values ("
					+ value.toString().replaceFirst(",", "") + ")";
		}
		return new BatchWriter(databaseConnectionConfig, insertSQL, limit);
	}
}
